import { defineStore } from 'pinia'
import { ref } from 'vue'
import DCYX_TEST_CENTER_API, {
  type UnitTestItem,
  type TestRecordItem,
  type TestDetailItem,
  type UnitTestListQueryParams,
  type TestRecordListQueryParams,
  type StartUnitTestPayload,
  type StartUnitTestResponse,
  type UnitTestPaper,
  type SubmitTestPaperPayload,
  type SubmitTestPaperResponse,
} from '@/api/dcyx/test-center.api'
import { store } from '@/store'

export const useDcyxTestCenterStore = defineStore('dcyx_test_center', () => {
  // 状态
  const unitTestList = ref<UnitTestItem[]>([])
  const testRecordList = ref<TestRecordItem[]>([])
  const testDetail = ref<TestDetailItem>({} as TestDetailItem)
  const testPaper = ref<UnitTestPaper>({} as UnitTestPaper)
  const loading = ref(false)
  const unitTestTotal = ref(0)
  const testRecordTotal = ref(0)

  /**
   * 获取教材单元测试列表
   * @param params 查询参数
   * @returns Promise<UnitTestItem[]>
   */
  function fetchUnitTestList(params: UnitTestListQueryParams) {
    return new Promise<UnitTestItem[]>((resolve, reject) => {
      loading.value = true
      DCYX_TEST_CENTER_API.getUnitTestList(params)
        .then((res) => {
          unitTestList.value = res.list
          unitTestTotal.value = res.total
          resolve(res.list)
        })
        .catch((error) => {
          unitTestList.value = []
          unitTestTotal.value = 0
          reject(error)
        })
        .finally(() => {
          loading.value = false
        })
    })
  }

  /**
   * 获取测试记录列表
   * @param params 查询参数
   * @returns Promise<TestRecordItem[]>
   */
  function fetchTestRecordList(params: TestRecordListQueryParams) {
    return new Promise<TestRecordItem[]>((resolve, reject) => {
      loading.value = true
      DCYX_TEST_CENTER_API.getTestRecordList(params)
        .then((res) => {
          console.log(res)
          testRecordList.value = res
          unitTestTotal.value = res.length
          resolve(res)
        })
        .catch((error) => {
          testRecordList.value = []
          testRecordTotal.value = 0
          reject(error)
        })
        .finally(() => {
          loading.value = false
        })
    })
  }

  /**
   * 开始单元测试
   * @param data 测试参数
   * @returns Promise<StartUnitTestResponse>
   */
  function startUnitTest(data: StartUnitTestPayload) {
    return new Promise<StartUnitTestResponse>((resolve, reject) => {
      DCYX_TEST_CENTER_API.startUnitTest(data)
        .then((res) => {
          resolve(res)
        })
        .catch((error) => {
          reject(error)
        })
    })
  }

  /**
   * 获取测试详情
   * @param testRecordId 测试记录ID
   * @returns Promise<TestDetailItem>
   */
  function fetchTestDetail(testRecordId: number) {
    return new Promise<TestDetailItem>((resolve, reject) => {
      loading.value = true
      DCYX_TEST_CENTER_API.getTestDetail(testRecordId)
        .then((res) => {
          testDetail.value = res
          resolve(res)
        })
        .catch((error) => {
          testDetail.value = {} as TestDetailItem
          reject(error)
        })
        .finally(() => {
          loading.value = false
        })
    })
  }

  /**
   * 获取单元测试试卷内容
   * @param unitId 单元ID
   * @returns Promise<UnitTestPaper>
   */
  function fetchTestPaper(unitId: number) {
    return new Promise<UnitTestPaper>((resolve, reject) => {
      loading.value = true
      DCYX_TEST_CENTER_API.getUnitTestPaper(unitId)
        .then((res) => {
          testPaper.value = res
          resolve(res)
        })
        .catch((error) => {
          testPaper.value = {} as UnitTestPaper
          reject(error)
        })
        .finally(() => {
          loading.value = false
        })
    })
  }

  /**
   * 播放单词音频
   * @param word 单词
   * @returns Promise<string>
   */
  function playWordAudio(word: string) {
    return new Promise<string>((resolve, reject) => {
      // 复用memory API的音频功能
      import('@/api/dcyx/memory.api').then(({ DCYX_MEMORY_API }) => {
        DCYX_MEMORY_API.getWordAudio(word)
          .then((blob) => {
            const realBlob = blob instanceof Blob ? blob : blob.data
            const url = URL.createObjectURL(realBlob)
            resolve(url)
          })
          .catch((error) => {
            reject(error)
          })
      })
    })
  }

  /**
   * 提交测试试卷
   * @param data 提交数据
   * @returns Promise<SubmitTestPaperResponse>
   */
  function submitTestPaper(data: SubmitTestPaperPayload) {
    return new Promise<any>((resolve, reject) => {
      loading.value = true
      DCYX_TEST_CENTER_API.submitTestPaper(data)
        .then((res) => {
          // console.log(res)
          resolve({
            msg: '提交成功',
          })
        })
        .catch((error) => {
          reject(error)
        })
        .finally(() => {
          loading.value = false
        })
    })
  }

  /**
   * 重置测试中心状态
   */
  function resetTestCenterStore() {
    unitTestList.value = []
    testRecordList.value = []
    testDetail.value = {} as TestDetailItem
    testPaper.value = {} as UnitTestPaper
    unitTestTotal.value = 0
    testRecordTotal.value = 0
    loading.value = false
  }

  return {
    // 状态
    unitTestList,
    testRecordList,
    testDetail,
    testPaper,
    loading,
    unitTestTotal,
    testRecordTotal,

    // 方法
    fetchUnitTestList,
    fetchTestRecordList,
    startUnitTest,
    fetchTestDetail,
    fetchTestPaper,
    submitTestPaper,
    playWordAudio,
    resetTestCenterStore,
  }
})

export function useDcyxTestCenterStoreHook() {
  return useDcyxTestCenterStore(store)
}
